/*
 * @Author: wenqingwu
 * @Date: 2022-01-20 09:17:37
 * @LastEditTime: 2022-04-01 11:08:04
 * @LastEditors: WenQingwu
 * @Description: 权限页面逻辑
 */
// 初始化数据为[];
let accessList = [
  // { acid: 1, acname: '权限管理', acdes: '系统管理员可以操作此模块，添加、修改、删除用户，添加、修改、删除权限，添加、修改、删除角色。' }
];
let roleList = []; // 角色列表数组
let roleSelectedId = []; //选中的角色的ID
let arrRoleName = [] // 选中的角色的名称
let AccessIdForRole = ''; // 当前要授权的权限ID
//1. 批量授权事件委托绑定：
$("tbody").on('click', '.set-role-access', showModalSetRoleAccess)
//2. 删除权限，事件委托
$("tbody").on('click', '.btn-delete', deleteAccess)

//3 addAccessBtn 添加权限后，保存，请求的后台数据
$("#addAccessBtn").click(function () {
  let accessName = $("#accessName").val();
  let accessDes = $("#accessDes").val();
  if (accessName.trim().length != 0 && accessDes.trim().length != 0) {
    $.ajax({
      url: "/api/addAccess",
      type: 'post',
      data: { accessName, accessDes },
      success(res) {
        // console.log(res);
        if (res.code === 0) {
          alert(res.msg)
          $("#accessName").val('');
          $("#accessDes").val('');
          $("#modalAddAccess").modal('hide')
        } else {
          alert(res.msg)
        }
      }
    })
  }


})

//4 modalSetRoleAccess 批量授权后，保存，请求后台数据
$("#setRoleAccessBtn").click(function () {
  $.ajax({
    url: '/api/addAccessToRole',
    type: 'post',
    data: { 'AccessIdForRole': AccessIdForRole, 'roleSelectedId': roleSelectedId.length === 0 ? '[]' : roleSelectedId },
    success(res) {
      console.log(res);
      if (res.code === 0) {
       
        alert(res.msg)
      } else {
        alert(res.msg)
      }
    }
  })
  $("#modalSetRoleAccess").modal('hide')
})

//5 查询权限,事件绑定
$('#searchAccessBtn').click(function () {
  let searchText = $("#search").val().trim()
  // 搜索指定列表数据，模糊查询
  getAccess(searchText, updateAccessTable);
})

//6 刷新数据,绑定事件 
$('#refreshBtn').click(function () {
  // 不传参数就获取所有列表数据
  getAccess("", updateAccessTable);
})

// 7 全选 权限列表的行
$("#checkAllAccess").change(function () {
  let state = this.checked;
  $("#accessListTbody input").each((index, item) => {
    // console.log(index,item)
    item.checked = state;
  })
})
// 8. 默认加载权限列表数据
$.ready(getAccess('', updateAccessTable))

// 9. 批量授权时,全选角色,并添加角色名称到上面的文本框
$("#checkAllRoles").change(function () {
  let state = this.checked;

  if (state) {
    arrRoleName = [];
    roleSelectedId = [];
    $("#rolelistModal input").each((index, item) => {
      item.checked = state;
      roleSelectedId.push(item.value)
      // 获取角色名称
      arrRoleName.push(getRoleName(item.value))

    })
    $('#selectRoles').val(arrRoleName.toString())

  } else {
    $("#rolelistModal input").each((index, item) => {
      item.checked = state;
    })
    roleSelectedId = [];
    arrRoleName = []
    $('#selectRoles').val('')
  }
  console.log(roleSelectedId, '============', arrRoleName)
})

// 10. 选择,取消选择角色
$('#rolelistModal').on('change', 'input', function () {
  let roleId = this.value;
  let roleName = getRoleName(this.value);

  if (this.checked) {
    arrRoleName.push(roleName)
    roleSelectedId.push(roleId)
    //  添加全选框的选中效果
    if (roleSelectedId.length === roleList.length && roleList.length != 0) {
      $('#checkAllRoles').get(0).checked = true;
    }
  } else {
    //  删除数组中的,角色name,ID

    arrRoleName.forEach((item, index) => {
      if (item == roleName) {
        arrRoleName.splice(index, 1)
      }
    })
    roleSelectedId.forEach((item, index) => {
      if (item == roleId) {
        roleSelectedId.splice(index, 1)
      }
    })
    //  取消全选框的选中效果
    if (roleSelectedId.length === 0) {
      $('#checkAllRoles').get(0).checked = false;
    }
  }
  $("#selectRoles").val(arrRoleName.toString())
  console.log(roleSelectedId, '============', arrRoleName)
})
// 显示批量授权模态框，并更新模态框中的内容：
async function showModalSetRoleAccess() {
  $("#modalSetRoleAccess").modal('show');
  $('#checkAllRoles').get(0).checked = false; // 取消全选
  $("#selectRoles").val('') //删除选择的角色
  arrRoleName=[]
  roleSelectedId = []
  roleList= []
  // 拿到ID，兑换成权限名称并显示在文本框中。
  let id = $(this).attr('data-id');
  AccessIdForRole = id;
  accessList.forEach(item => {
    if (item.acid === parseInt(id)) {
      $("#accessName2").val(item.acname)
    }
  })

  // 已经授权的数据
  const checkedRoleId = await getAccessOfRole(id);
  console.log(checkedRoleId, "////////////////")
  checkedRoleId.forEach(item=>{
    roleSelectedId.push(item.rid)
  })
  // roleSelectedId= ;
  // 获取角色列表，并更新模态中的表格
  roleList = await getRoleList('');
  console.log(roleList, "////////////////")


  $("#rolelistModal").html('') //清空后再添加
  await roleList.forEach(item => {
    let bChecked = checkedRoleId.some((el) => el.rid === item.r_id);
    bChecked&&(arrRoleName.push(item.r_name))
    $("#rolelistModal").append(
      `<tr>
        <td><input type="checkbox" value="${item.r_id}" class="check-item-roles" ${bChecked?'checked':''}></td>
        <td>${item.r_name}</td>
        <td>${item.r_des}</td>
      </tr>`);

  })

  $("#selectRoles").val(arrRoleName.toString())
 
  arrRoleName.length === roleList.length && ($("#checkAllRoles").get(0).checked = true)
  
}
// 删除权限
async function deleteAccess() {
  // alert('删除成功')
  let acid = $(this).attr("data-id");

  $.ajax({
    url: '/api/delAccess',
    type: 'post',
    data: { acid },
    success(res) {
      console.log(res);
      if (res.code === 0) {
        alert(res.msg)
        getAccess("", updateAccessTable);
      } else {
        alert(res.msg)
      }
    }
  })

}

// 更新权限列表表格
function updateAccessTable(arr) {
  let tbody = $("#accessListTbody")
  tbody.html('')
  arr.forEach(item => {
    tbody.append(`
    <tr>
      <td>
        <input type="checkbox" >
      </td>
      <td>${item.acname}</td>
      <td class="text-muted">${item.acdes}</td>
      <td>
        <button type="button" class="btn btn-link text-info set-role-access" data-id="${item.acid}">批量授权</button>
        <button type="button" class="btn btn-link text-danger btn-delete" data-id="${item.acid}">删除</button>
      </td>
    </tr>
    `)
  })
}
// 获取权限列表
function getAccess(searchText, callback) {
  $.ajax({
    url: '/api/getAccess',
    type: 'get',
    data: { searchText },
    success(res) {
      console.log(res);
      if (res.code === 0) {
        accessList = res.data;
        callback(res.data)
        // alert(res.msg)
      } else {
        alert(res.msg)
      }
    }
  })
}


// 通过角色ID,返回角色的名称,
function getRoleName(id) {
  if (!id) throw new Error('ID 必须要传.')

  let r_name = ''
  for (let i = 0; i < roleList.length; i++) {
    if (roleList[i].r_id == id) {
      r_name = roleList[i].r_name;
      break;
    }
  }
  return r_name;
}

// 获取一个权限的已授权角色的数据,返回数组;
async function getAccessOfRole(id) {
  if (!id) throw new Error('权限ID 必须要传.')
  console.log(id)
  return new Promise((resolve, reject) => {
    $.ajax({
      url: '/api/getRoleForAccess',
      type: 'get',
      data: { "AccessIdForRole": id },
      success(res) {
        if (res.code === 0) {
          resolve(res.data);
        } else {
          reject(res.msg)
        }
      }
    })
  })
}
// 获取角色列表灵气
async function getRoleList(searchText) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: '/api/getRole',
      type: 'get',
      data: { searchText },
      success(res) {

        if (res.code === 0) {

          resolve(res.data)
        } else {
          reject(res.msg)
        }
      }
    })
  })

}
